package com.triones.api.service.third;

import cn.hutool.core.convert.Convert;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.config.PhotonPayConfig;
import com.ruoyi.common.constant.PhpApiPathConstants;
import com.ruoyi.common.utils.PhpApiSignUtils;
import com.triones.api.entity.bo.PhotonPayFileUploadBO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 工具接口（调用第三方）业务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ApiThirdCommonServiceImpl implements ApiThirdCommonService {

    private final PhotonPayConfig photonPayConfig;

    private final PhotonPayService photonPayService;

    private final OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(15, TimeUnit.SECONDS)
        .build();

    @Override
    public String photonPayFileUpload(PhotonPayFileUploadBO bo) throws IOException {
        return sendUploadPost(bo.getFile(),bo.getBusinessKey());
    }

    /**
     * 发送文件上传post请求
     * @return
     */
    public String sendUploadPost(MultipartFile file, String businessKey) throws IOException {
        // 确定文件的 MediaType
        MediaType mediaType;
        String originalFilename = file.getOriginalFilename();
        if (originalFilename != null) {
            if (originalFilename.toLowerCase().endsWith(".png")) {
                mediaType = MediaType.parse("image/png");
            } else if (originalFilename.toLowerCase().endsWith(".jpg") || originalFilename.toLowerCase().endsWith(".jpeg")) {
                mediaType = MediaType.parse("image/jpeg");
            } else {
                throw new IllegalArgumentException("Unsupported file type: " + originalFilename);
            }
        } else {
            throw new IllegalArgumentException("File name is null");
        }

        RequestBody body = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", originalFilename,
                RequestBody.create(file.getBytes(), mediaType)) // 文件部分
            .build();
        Request request = new Request.Builder()
            .url(photonPayConfig.getUrl() + PhpApiPathConstants.fileApiUpload + "/" + businessKey)
            .post(body)
            .header("content-type", mediaType.toString())
            .header("X-PD-TOKEN", photonPayService.getPhotonPayToken())
            .build();
        System.out.println("request = " + request);
        try (Response response = client.newCall(request).execute()) {
            System.out.println("response = " + response);
            if (response.isSuccessful()) {
                ObjectMapper objectMapper = new ObjectMapper();
                String responseBody = response.body().string();
                log.info("成功 - 响应参数 : {}", responseBody);
                Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
                if (responseMap.get("code").equals("0000")) {
                    return responseMap.get("data").toString();
                } else {
                    throw new SecurityException(Convert.toStr(responseMap.get("msg")));
                }
            } else {
                log.error("Request failed: {}", response.code());
                log.error("Request failed msg: {}", response);
                System.out.println("失败 - 响应参数 ：" + Convert.toStr(response.code()));
                throw new SecurityException("请求出错");
            }
        } catch (IOException e) {
            log.error("IOException occurred: ", e);
            throw new SecurityException("请求异常");
        }
    }
}
